package com.dstz.agilebpm.springcloud.zuul.filter;

import com.dstz.agilebpm.springcloud.zuul.enums.ServiceProviderEnum;
import com.dstz.base.api.response.impl.ResultMsg;
import com.google.common.collect.ImmutableMap;
import com.netflix.zuul.ExecutionStatus;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.ZuulFilterResult;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author wacxhs
 */
@Log
@Component
public class TokenValidateFilter extends ZuulFilter {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        final String accessToken = StringUtils.defaultString(requestContext.getRequest().getHeader("accessToken"));
        ResultMsg resultMsg = restTemplate.postForEntity(String.format("http://%s/auth/token/validate", ServiceProviderEnum.AUTH_SERVICE.getValue()), ImmutableMap.of("accessToken", accessToken), ResultMsg.class).getBody();
        if(resultMsg.getIsOk()){
            return new ZuulFilterResult(ExecutionStatus.SUCCESS);
        }else{
            return new ZuulFilterResult(ExecutionStatus.FAILED);
        }
    }
}
